package com.le.tester.imooc.oldfairy;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * createTime：2021/8/26 16:21
 * description：继承java使用的aqs
 */
public class LMutex extends AbstractQueuedSynchronizer {

    @Override
    protected boolean tryRelease(int arg) {
        return compareAndSetState(2, 0);
    }

    @Override
    protected boolean tryAcquire(int arg) {
        return compareAndSetState(0, 2);
    }

    public static int i;

    public static void main(String[] args) throws InterruptedException {
        LMutex lMutex = new LMutex();
        Thread t1 = new Thread(() -> {
            lMutex.acquire(0);
            for (int j = 0; j < 10000; j++) {
                i++;
            }
            lMutex.release(0);
        });
        t1.start();

        Thread t2 = new Thread(() -> {
            lMutex.acquire(0);
            for (int j = 0; j < 10000; j++) {
                i++;
            }
            lMutex.release(0);
        });
        t2.start();

        t1.join();
        t2.join();

        System.out.println("i is " + i);
    }
}
